package com.westar.tv.http;

import com.westar.tv.Config;
import com.westar.tv.CustomApplication;
import com.westar.tv.SPKeys;
import com.westar.tv.Version;
import com.westar.tv.utils.SharePreferencesUtils;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * Created by wang-dev
 */
public class AppClient {

    //请求超时时间
    private static final int DEFAULT_TIMEOUT = 5;

    private Retrofit retrofit;

    private ApiStores apiStores;

    private AppClient() {
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder clientBuilder = new OkHttpClient().newBuilder();
        //超时时间
        clientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        //地址
        String url = (String) SharePreferencesUtils.get(CustomApplication.getInstance(), SPKeys.DEFAULT_SP_FILE_NAME, SPKeys.SERVER_URL, Config.SERVER_URL);
        //API请求地址
        String API_BASE_URL = "http://" + url + "/app/";
        //设置拦截器
        retrofit = new Retrofit.Builder()
                .client(clientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(API_BASE_URL)
                .build();

        apiStores = retrofit.create(ApiStores.class);
    }

    //在访问AppClient时创建单例
    private static class SingletonHolder {
        private static final AppClient INSTANCE = new AppClient();
    }

    //获取单例
    public static AppClient getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * 订阅
     *
     * @param o
     * @param s
     * @param <T>
     */
    private <T> void toSubscribe(Observable<T> o, Subscriber<T> s) {
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }

    /**
     * 统一处理HttpResult的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     * @param <T>
     */
    private class HttpResultFunc<T> implements Func1<HttpResult<T>, T> {
        @Override
        public T call(HttpResult<T> httpResult) {
            if (httpResult.getCode() != HttpResult.CODE_OK) {
                throw new ApiException(httpResult.getCode(), httpResult.getMsg());
            }
            return httpResult.getData();
        }
    }

    /**
     * 检查更新
     *
     * @param subscriber
     */
    public void checkVersion(Subscriber<Version> subscriber, String name) {
        final Observable<Version> observable = apiStores.checkVersion(name)
                .map(new HttpResultFunc<Version>());

        toSubscribe(observable, subscriber);
    }

}
